package com.trade.common.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.time.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 条件查询封装类
 */
public class SearchFilter {
	//EQ(等于), IN(在值数组中), ISNULL(非空), LIKE(包含), GT(大于), LT(小于),
	//GTE(大于等于), LTE(小于等于), NE(不等于),LIKEIGNORE(包含，忽略大小写)
	public enum Operator {
		EQ, IN, ISNULL, LIKE, GT, LT, GTE, LTE, NE,LIKEIGNORE
	}

	public String fieldName;
	public Object value;
	public Operator operator;

	public SearchFilter(String fieldName, Operator operator, Object value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	/**
	 * 将查询条件字符串转换为List<SearchFilter>形式
	 * @param conditionFilter
	 *              查询条件的json数组，格式为[{property:"字段名",option:"操作类型",value:"值",propertytype:"数据类型"}]
	 *              其中option的值有EQ(等于), IN(在值数组中), ISNULL(非空), LIKE(包含), GT(大于), LT(小于),
	 *              		GTE(大于等于), LTE(小于等于), NE(不等于),LIKEIGNORE(包含，忽略大小写)
	 * @return
	 */
	public static List<SearchFilter> parse(String conditionFilter) {
		//返回结果声明
		List<SearchFilter> filters = new ArrayList<SearchFilter>();
		//如果条件JSONArray字符串可用，则将字符串转换为查询条件Map
		if (XaUtil.isNotEmpty(conditionFilter)){
			JSONArray searchArray=JSONArray.fromObject(conditionFilter);
			JSONObject searchJsonObj = null;
			for (int i = 0; i < searchArray.size(); i++) {
				searchJsonObj = searchArray.getJSONObject(i);
				Object value = searchJsonObj.getString("value");

				//判断是否是短日期格式的参数
				if("DATETIME".equalsIgnoreCase(searchJsonObj.getString("propertytype"))){
					String fieldValue = (String)value;
					if(XaUtil.isNotEmpty(fieldValue)){
						value= UnionDateUtil.formatStr(fieldValue, UnionDateUtil.YYYYMMDDHHMMSS);
					}
				}else if("DATE".equalsIgnoreCase(searchJsonObj.getString("propertytype"))){
					String fieldValue = (String)value;
					if(XaUtil.isNotEmpty(fieldValue)){
						if("LTE".equalsIgnoreCase(searchJsonObj.getString("option"))){
							Date d= UnionDateUtil.formatStr(fieldValue, UnionDateUtil.YYYYMMDD);
							value=DateUtils.addDays(d, 1);
						}else{
							value= UnionDateUtil.formatStr(fieldValue, UnionDateUtil.YYYYMMDD);
						}
					}
				}

				//创建查询条件并将查询条件放入Map中
				SearchFilter filter = new SearchFilter(searchJsonObj.getString("property"), Operator.valueOf(searchJsonObj.getString("option")), value);
				if(XaUtil.isNotEmpty(searchJsonObj.getString("value"))){
					filters.add(filter);
				}
			}
		}
		//添加查询条件，只查询数据状态正常的数据
		SearchFilter dataFlagFilter = new SearchFilter("dataFlag", Operator.EQ, Constants.DATA_FLAG_OK);
		filters.add(dataFlagFilter);

		return filters;
	}
}
